import http from '../common/http.js'
import {
	userStore
} from '../store/user.js'
export const getCode = () => {
	const promise = new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin', //使用微信登录
			success: function(loginRes) {
				console.log(loginRes.code);
				if (loginRes && loginRes.code) {
					resolve(loginRes.code)
				} else {
					reject(loginRes)
				}
			}
		});
	}).catch(res => {
		uni.showToast({
			icon: 'none',
			title: res.errMsg || '获取code失败'
		})
	})
	return promise;
}

export const wxLoginApi = (code) => {
	return http.post('/wxapi/user/wxLogin', {
		code: code
	})
}

export const getUserInfoApi = (parm) => {
	return http.get("/wxapi/wxUser/getUserInfo", parm)
}

export const userLogin = async () => {
	const store = userStore()
	let res = await getCode()
	const {
		data
	} = await wxLoginApi(res)
	console.log('Login')
	console.log(data)
	if (data) {
		uni.setStorageSync('openid', data.openid)
		uni.setStorageSync('sessionKey', data.sessionKey)
	}
	let result = await getUserInfoApi({
		openid: data.openid
	})
	console.log(result.data)
	if (result.data && result.data.avatarUrl) {
		store.avatarUrl = result.data.avatarUrl
		uni.setStorageSync('avatarUrl', result.data.avatarUrl)
	}
	if (result.data && result.data.nickName) {
		store.nickName = result.data.nickName
		uni.setStorageSync('nickName', result.data.nickName)
	}
}

export const addAddressApi = (parm) => {
	return http.post("/wxapi/address", parm)
}

export const addressListApi = (parm) => {
	return http.get("/wxapi/address/list", parm)
}

export const editAddressApi = (parm) => {
	return http.put("/wxapi/address", parm)
}
// 默认地址
export const getAddressApi = (parm) => {
	return http.get("/wxapi/address/getAddress", parm)
}

export const uploadImageApi = (parm) => {
	return http.upload(parm)
}

export const saveOrUpdateApi = (parm) => {
	return http.post("/wxapi/wxUser/saveOrUpdate", parm)
}

export const addCommentApi = (parm) => {
	return http.post("/wxapi/comment/addComment", parm)
}